package com.putong35.easyui.picture.picker;

import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.putong35.common.app.FileManager;
import com.putong35.common.baseactfrag.activity.BaseActivity;
import com.putong35.common.imageloader.ImageLoader;
import com.putong35.common.utils.DimensionUtil;
import com.putong35.common.utils.EasyToast;
import com.putong35.easyui.R;
import com.putong35.easyui.picture.browser.constant.Constant;
import com.putong35.easyui.picture.browser.view.PictureBrowserActivity;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;


/**
 * 从相册选择照片
 *
 * @Author: PengWeiwei
 * @E-mail: pengveivei@sina.cn
 * @CreateDate: 2017-04-07
 * @Version: 1.0.0
 */
public class SelectAlbumActivity extends BaseActivity implements View.OnClickListener {
    public static final String INTENT_SELECTED_PICTURE = "intent_selected_picture";

    private ImageAdapter mImgAdapter;
    private final static int SCAN_OK = 1;
    private TextView tvSelectNum;
    private CheckBox cbAlbumToggle;
    private AlbumAdapter mAlbumAdapter;
    private RelativeLayout mTitleRlyt;
    private TextView tvCancleView;
    /**
     * 最多选择图片的个数
     */
    public static int MAX_NUM = 9;
    public int mCheckNum = 0;
    public static final int TAKE_PICTURE = 520;
    public static final int PREVIEW = 205;

    public static final String INTENT_MAX_NUM = "intent_max_num";
    public static final String RELEASE_IMGS_NUM = "intent_img_num";

    /**
     * 临时的辅助类，用于防止同一个文件夹的多次扫描
     */
    private HashMap<String, Integer> tmpDir = new HashMap<>();
    private ArrayList<ImageFloder> mDirPaths = new ArrayList<>();

    /**
     * 已选择的图片
     */
    private ArrayList<String> mSelectedPicture = new ArrayList<>();
    private String cameraPath = null;
    private ImageFloder imageAll = null;
    private RecyclerView mRcPicGrid;

    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case SCAN_OK:
                    mImgAdapter = new ImageAdapter(imageAll);
                    mRcPicGrid.setAdapter(mImgAdapter);
                    break;
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
        initGetIntent();
    }

    @Override
    public View createDataView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.picture_activity_select_album, null);
    }


    protected void initGetIntent() {
        MAX_NUM = getIntent().getIntExtra(INTENT_MAX_NUM, 3);
        imageAll = new ImageFloder();
        imageAll.setDir("/所有图片");
        mCheckNum = getIntent().getIntExtra(RELEASE_IMGS_NUM, 0);
        getThumbnail();
    }


    public void initView() {

        initTitle();

        tvSelectNum = (TextView) findViewById(R.id.ac_select_album_select_num);
        mRcPicGrid = (RecyclerView) findViewById(R.id.ac_select_album_pic_list);
//        cbAlbumToggle = (CheckBox) findViewById(R.id.ac_select_album_toggle);

        findViewById(R.id.ac_select_album_title_preview).setOnClickListener(this);

        findViewById(R.id.ac_select_album_pic_enter).setOnClickListener(this);
        tvSelectNum.setText("" + mCheckNum);
        mRcPicGrid.setLayoutManager(new GridLayoutManager(this, 4));
        mRcPicGrid.setItemAnimator(new DefaultItemAnimator());
        mRcPicGrid.addItemDecoration(new DividerGridItemDecoration(getResources().getDrawable(R.drawable.picture_grid_recyclerview_gray)));
        getCustomToolbar().setCenterView(mTitleRlyt);
    }

    private void initTitle() {
        mTitleRlyt = new RelativeLayout(this);
        RelativeLayout.LayoutParams titleBarLayoutparams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        RelativeLayout.LayoutParams tvAlbumLayoutparams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT);
        RelativeLayout.LayoutParams tvCancleLayoutparams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT);


        mTitleRlyt.setLayoutParams(titleBarLayoutparams);
        cbAlbumToggle = new CheckBox(this);
        cbAlbumToggle.setButtonDrawable(new ColorDrawable(Color.TRANSPARENT));
        cbAlbumToggle.setText(getString(R.string.checkbox_album_name));
        cbAlbumToggle.setTextColor(getResources().getColor(R.color.text_color_gray_black));
        Drawable albumToggleDrawable = getResources().getDrawable(R.drawable.picture_btn_check_album);
        albumToggleDrawable.setBounds(0, 0, albumToggleDrawable.getMinimumWidth(), albumToggleDrawable.getMinimumHeight());
        cbAlbumToggle.setCompoundDrawables(null, null, albumToggleDrawable, null);
        cbAlbumToggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    showPopupWindow(cbAlbumToggle);
                    backgroundAlpha(0.5f);
                }
            }
        });
        tvAlbumLayoutparams.addRule(RelativeLayout.CENTER_IN_PARENT);

        mTitleRlyt.addView(cbAlbumToggle, tvAlbumLayoutparams);

        tvCancleView = new TextView(this);
        tvCancleView.setText(getString(android.R.string.cancel));
        tvCancleView.setTextColor(getResources().getColor(R.color.app_main_color_cannel));
        tvCancleView.setTextSize(DimensionUtil.px2dip(this, getResources().getDimension(R.dimen.size_select_album_btn)));
        tvCancleView.setGravity(Gravity.CENTER_VERTICAL);
        tvCancleView.setPadding(DimensionUtil.dip2px(this, 14), 0, DimensionUtil.dip2px(this, 14), 0);
        tvCancleView.setOnClickListener(this);
        tvCancleLayoutparams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
        mTitleRlyt.addView(tvCancleView, tvCancleLayoutparams);
    }


    @Override
    public void onClick(View view) {
        int i = view.getId();
        int hascode = view.hashCode();

        if (hascode == tvCancleView.hashCode()) {
            finish();

        } else if (i == R.id.ac_select_album_pic_enter) {

            if ("0".equals(mCheckNum) || mCheckNum == 0) {
                EasyToast.showToast(getBaseContext(), getString(R.string.select_pic_atleast));
            } else {
                Intent intent = new Intent().putExtra(INTENT_SELECTED_PICTURE, mSelectedPicture);
                setResult(RESULT_OK, intent);
                finish();
            }


        } else if (i == R.id.ac_select_album_title_preview) {
            if (mSelectedPicture.size() > 0) {
                PictureBrowserActivity.watchPhoto(this, mSelectedPicture, Constant.RESULT_CODE_SELETE);
            } else {
                Toast.makeText(this, R.string.selected_picture_none, Toast.LENGTH_SHORT).show();
            }

        } else {

        }
    }


    /**
     * 图片列表适配器
     */
    class ImageAdapter extends RecyclerViewAdapter<ImageAdapter.ViewHolder> {
        private List<String> images = new ArrayList<>();

        public ImageAdapter(ImageFloder imageFloder) {
            super();
            images.addAll(imageFloder.images);
            mSelectedPicture.clear();
        }


        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

            View v = LayoutInflater.from(parent.getContext()).inflate(
                    R.layout.picture_item_img_album_ac, parent, false);
            ViewHolder holder = new ViewHolder(v);
            holder.img = (ImageView) v.findViewById(R.id.item_img_ac_album);
            holder.cbSelected = (CheckBox) v.findViewById(R.id.cbSelected);
            return holder;
        }

        public void setImagesList(ImageFloder imageFloder) {
            images.clear();
//            mSelectedPicture.clear();
            images.addAll(imageFloder.images);
            mCheckNum = mSelectedPicture.size();
            tvSelectNum.setText(mCheckNum + "");
            notifyDataSetChanged();
        }

        @Override
        public int getItemCount() {
            return images.size();
        }

        @Override
        public void onBindHolder(RecyclerView.ViewHolder viewHolder, final int i) {

            final ImageAdapter.ViewHolder holder = (ImageAdapter.ViewHolder) viewHolder;
            View.OnClickListener check_listener = new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mSelectedPicture.contains(images.get(i))) {
                        mCheckNum--;
                        holder.cbSelected.setChecked(false);
                        tvSelectNum.setText("" + mCheckNum);
                        mSelectedPicture.remove(images.get(i));
                    } else {
                        if (mCheckNum + 1 > MAX_NUM) {
                            Toast.makeText(SelectAlbumActivity.this, "最多选择" + MAX_NUM + "张", Toast.LENGTH_SHORT).show();
                        } else {
                            mCheckNum++;
                            holder.cbSelected.setChecked(true);
                            tvSelectNum.setText(mCheckNum + "");
                            mSelectedPicture.add(images.get(i));
                        }
                    }
                }
            };

            if (mSelectedPicture.contains(images.get(i))) {
                holder.cbSelected.setChecked(true);
            } else {
                holder.cbSelected.setChecked(false);
            }

            String path = "file://" + images.get(i);

            ImageLoader.with(SelectAlbumActivity.this)
                    .load(path)
                    .skipMemory(true)
                    .into(holder.img)
                    .start();

            holder.img.setOnClickListener(check_listener);

            holder.cbSelected.setOnClickListener(check_listener);


        }


        class ViewHolder extends RecyclerView.ViewHolder {
            CheckBox cbSelected;
            ImageView img;

            public ViewHolder(View itemView) {
                super(itemView);
            }
        }
    }

    /**
     * 相册列表适配器
     */
    class AlbumAdapter extends RecyclerViewAdapter<AlbumAdapter.ViewHolder> {

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

            View v = LayoutInflater.from(parent.getContext()).inflate(
                    R.layout.picture_item_album_text, parent, false);
            ViewHolder holder = new ViewHolder(v);
            holder.album = (TextView) v.findViewById(R.id.item_album_text);
            holder.num = (TextView) v.findViewById(R.id.item_album_num);
            return holder;
        }

        @Override
        public int getItemCount() {
            return mDirPaths.size() + 1;
        }

        @Override
        public void onBindHolder(RecyclerView.ViewHolder viewHolder, final int i) {

            final AlbumAdapter.ViewHolder holder = (AlbumAdapter.ViewHolder) viewHolder;
            if (i == 0) {
                holder.album.setText(imageAll.getName());
                holder.num.setText("( " + imageAll.images.size() + " )");
            } else {
                holder.album.setText(mDirPaths.get(i - 1).getName());
                holder.num.setText("( " + mDirPaths.get(i - 1).images.size() + " )");
            }

        }

        class ViewHolder extends RecyclerView.ViewHolder {
            TextView album, num;

            public ViewHolder(View itemView) {
                super(itemView);
            }
        }
    }

    private void showPopupWindow(View view) {
        // 一个自定义的布局，作为显示的内容
        View contentView = LayoutInflater.from(this).inflate(
                R.layout.picture_pop_selectalbum, null);
        RecyclerView rcvSelectalbum = (RecyclerView) contentView.findViewById(R.id.rc_pop_selectalbum_list);
        rcvSelectalbum.setLayoutManager(new LinearLayoutManager(this));
        if (mAlbumAdapter == null) {
            mAlbumAdapter = new AlbumAdapter();
        }
        rcvSelectalbum.setAdapter(mAlbumAdapter);
        int height;
        if (mDirPaths.size() < 5) {
            height = (mDirPaths.size() + 1) * getResources().getDimensionPixelSize(R.dimen.item_height_album_allaublum);
        } else {
            height = 5 * getResources().getDimensionPixelSize(R.dimen.item_height_album_allaublum);
        }
        final PopupWindow popupWindow = new PopupWindow(contentView,
                DimensionUtil.dip2px(this, 220), height, true);
        popupWindow.setTouchable(true);

        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {

            public void onDismiss() {
                backgroundAlpha(1);
                cbAlbumToggle.setChecked(false);
            }
        });

        // 如果不设置PopupWindow的背景，无论是点击外部区域还是Back键都无法dismiss弹框
        // 我觉得这里是API的一个bug
        popupWindow.setBackgroundDrawable(getResources().getDrawable(R.drawable.picture_rc_pop_selectalbum_list));
        int hight = DimensionUtil.dip2px(this, 3);
        //popupWindow.showAtLocation(view, Gravity.TOP, 0,0);
        popupWindow.showAsDropDown(view, -view.getWidth(), hight);
        // 设置好参数之后再show
        mAlbumAdapter.setOnItemClickLitener(new RecyclerViewAdapter.OnItemClickLitener() {
            @Override
            public void onItemClick(View views, int position) {
                if (position == 0) {
                    mImgAdapter.setImagesList(imageAll);
                    cbAlbumToggle.setText(R.string.all_picture);
                } else {
                    mImgAdapter.setImagesList(mDirPaths.get(position - 1));
                    cbAlbumToggle.setText(mDirPaths.get(position-1).getName());
                }
                popupWindow.dismiss();
            }

            @Override
            public boolean onItemLongClick(View views, int position) {
                return false;
            }
        });
    }

    /**
     * 设置添加屏幕的背景透明度
     */
    public void backgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = bgAlpha;
        getWindow().setAttributes(lp);
    }

    /**
     * 使用相机拍照
     *
     * @version 1.0
     * @author
     */
    protected void goCamare() {
        if (mSelectedPicture.size() + 1 > MAX_NUM) {
            Toast.makeText(this, "最多选择" + MAX_NUM + "张", Toast.LENGTH_SHORT).show();
            return;
        }
        Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        Uri imageUri = getOutputMediaFileUri();
        openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        startActivityForResult(openCameraIntent, TAKE_PICTURE);
    }

    /**
     * 用于拍照时获取输出的Uri
     *
     * @return
     * @version 1.0
     * @author zyh
     */
    protected Uri getOutputMediaFileUri() {
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        File mediaFile = new File(FileManager.getImagePath(this) + File.separator + "IMG_" + timeStamp + ".jpg");
        cameraPath = mediaFile.getAbsolutePath();
        return Uri.fromFile(mediaFile);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK) {
            return;
        }
        if (cameraPath != null) {
            mSelectedPicture.add(cameraPath);
            Intent data2 = new Intent();
            data2.putExtra(INTENT_SELECTED_PICTURE, mSelectedPicture);
            setResult(RESULT_OK, data2);
        }

        if (requestCode == PREVIEW && data != null) {
            Intent intent = getIntent();
            ArrayList<String> imgs = (ArrayList<String>) data.getSerializableExtra(INTENT_SELECTED_PICTURE);
            intent.putExtra(INTENT_SELECTED_PICTURE, imgs);
            setResult(RESULT_OK, intent);
        }
    }

    /**
     * 得到缩略图
     */
    private void getThumbnail() {

        new Thread(new Runnable() {

            @Override
            public void run() {
                Cursor mCursor = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                        new String[]{MediaStore.Images.ImageColumns.DATA}, "", null,
                        MediaStore.MediaColumns.DATE_ADDED + " DESC");
                if (mCursor.moveToFirst()) {
                    int _date = mCursor.getColumnIndex(MediaStore.Images.Media.DATA);
                    do {
                        // 获取图片的路径
                        String path = mCursor.getString(_date);
                        // Log.e("TAG", path);
                        imageAll.images.add(path);
                        if (TextUtils.isEmpty(imageAll.getFirstImagePath())) {
                            imageAll.setFirstImagePath(path);
                            imageAll.setDir("/所有图片");
                        }
                        // 获取该图片的父路径名
                        File parentFile = new File(path).getParentFile();
                        if (parentFile == null) {
                            continue;
                        }
                        ImageFloder imageFloder = null;
                        String dirPath = parentFile.getAbsolutePath();
                        if (!tmpDir.containsKey(dirPath)) {
                            // 初始化imageFloder
                            imageFloder = new ImageFloder();
                            imageFloder.setDir(dirPath);
                            imageFloder.setFirstImagePath(path);
                            mDirPaths.add(imageFloder);
                            tmpDir.put(dirPath, mDirPaths.indexOf(imageFloder));
                        } else {
                            imageFloder = mDirPaths.get(tmpDir.get(dirPath));
                        }
                        imageFloder.images.add(path);
                    } while (mCursor.moveToNext());
                }
                mCursor.close();
                mHandler.sendEmptyMessage(SCAN_OK);
                tmpDir = null;
            }
        }).start();
    }

    @Override
    protected void onDestroy() {
        ImageLoader.with(this).clear();
        super.onDestroy();
    }
}
